// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.commons.notifications;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-2-27 qiang.zhang $
 * 
 */
public abstract class AbstractNotificationsManager implements IDenguesNotificationsManager, IPropertyChangeListener {

    private static final long DELAY_OPEN = 5 * 1000;

    private static final boolean runSystem = true;

    private static final long DEFAULT_DELAY_CLOSE = 8 * 1000;

    protected AbstractNotificationPopup popup;

    private final Set<AbstractNotification> notifications = new HashSet<AbstractNotification>();

    private final Set<AbstractNotification> currentlyNotifying = Collections.synchronizedSet(notifications);

    private final List<INotificationProvider> notificationProviders = new ArrayList<INotificationProvider>();

    private final Job openJob = new Job(getNotificationJobName()) {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
         */
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {

                if (!PlatformUI.getWorkbench().getDisplay().isDisposed()) {
                    PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

                        /*
                         * (non-Javadoc)
                         * 
                         * @see java.lang.Runnable#run()
                         */
                        public void run() {
                            collectNotifications();
                            synchronized (AbstractNotificationsManager.class) {
                                if (currentlyNotifying.size() > 0) {
                                    // popup.close();
                                    showPopup();
                                }
                            }
                        }
                    });
                }
            } finally {
                if (isScheduleEnable()) {
                    if (popup != null) {
                        schedule(getScheduleMilis() + DEFAULT_DELAY_CLOSE / 2);
                    } else {
                        schedule(getScheduleMilis() + DELAY_OPEN);
                    }
                }
            }

            if (monitor.isCanceled())
                return Status.CANCEL_STATUS;

            return Status.OK_STATUS;
        }

    };

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.notifications.IDenguesNotificationsManager#showPopup()
     */
    public void showPopup() {
        if (popup != null) {
            popup.close();
        }

        Shell shell = new Shell(PlatformUI.getWorkbench().getDisplay());
        popup = createNotificationPopup(shell);
        List<AbstractNotification> toDisplay = new ArrayList<AbstractNotification>(currentlyNotifying);
        Collections.sort(toDisplay);
        popup.setContents(toDisplay);
        cleanNotified();
        popup.setBlockOnOpen(false);
        popup.open();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "createNotificationPopup".
     * 
     * @param shell
     * @return
     */
    protected abstract AbstractNotificationPopup createNotificationPopup(Shell shell);

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getScheduleMilis".
     * 
     * @return
     */
    protected abstract long getScheduleMilis();

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "isScheduleEnable".
     * 
     * @return
     */
    protected abstract boolean isScheduleEnable();

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getNotificationJobName".
     * 
     * @return
     */
    protected abstract String getNotificationJobName();

    public void stopNotification() {
        openJob.cancel();
        // closeJob.cancel();
        // if (popup != null) {
        // popup.close();
        // }
    }

    private void collectNotifications() {
        for (INotificationProvider provider : notificationProviders) {
            currentlyNotifying.addAll(provider.getNotifications());
        }
    }

    private void cleanNotified() {
        currentlyNotifying.clear();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.notifications.IDenguesNotificationsManager#addNotificationProvider(org.dengues.core.notifications.INotificationProvider)
     */
    public void addNotificationProvider(INotificationProvider notificationProvider) {
        notificationProviders.add(notificationProvider);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.notifications.IDenguesNotificationsManager#removeNotificationProvider(org.dengues.core.notifications.INotificationProvider)
     */
    public void removeNotificationProvider(INotificationProvider notificationProvider) {
        notificationProviders.remove(notificationProvider);
    }

    public void startNotification(long initialStartupTime) {
        if (!openJob.cancel()) {
            try {
                openJob.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        openJob.setSystem(runSystem);
        openJob.schedule(initialStartupTime);
    }

    /**
     * public for testing purposes
     */
    public Set<AbstractNotification> getNotifications() {
        synchronized (AbstractNotificationsManager.class) {
            return currentlyNotifying;
        }
    }

}
